package com.chisheng.service.impl;

import com.chisheng.common.Page;
import com.chisheng.student.Student;
import com.chisheng.mapper.StudentMapper;
import com.chisheng.service.StudentService;
import com.chisheng.common.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 学生服务默认实现
 *
 * @author chisheng
 * @since 2021-11-05
 */
public class StudentServiceImpl implements StudentService {

    /**
     * SQL 会话
     */
    private final SqlSession session;

    /**
     * 学生 DAO
     */
    private final StudentMapper studentDao;

    /**
     * 初始化 SqlSession 实例
     */
    public StudentServiceImpl() {
        this.session = MybatisUtils.getSqlSession();
        this.studentDao = session.getMapper(StudentMapper.class);
    }

    @Override
    public boolean add(Student student) {
        try {
            int result = studentDao.insertOne(student);
            session.commit();
            return result >= 1;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public boolean remove(Integer id) {
        try {
            int result = studentDao.deleteById(id);
            session.commit();
            return result >= 1;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public boolean update(Student student) {
        try {
            int result = studentDao.updateById(student);
            session.commit();
            return result >= 1;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public Student query(Integer id) {
        try {
            return studentDao.findById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public Page<Student> queryPage(int current, int size) {
        try {
            int offset = (current - 1) * size;
            long total = studentDao.count();
            List<Student> rows = studentDao.findStudentLimit(offset, size);
            return new Page<>(current, size, total, rows);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

}
